package work.comeback.omo.controller.servlet.auth;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import work.comeback.omo.util.common.CaptchaGenerator;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet("/api/auth/captcha")
public class CaptchaServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(CaptchaServlet.class);
    private final CaptchaGenerator captchaGenerator = new CaptchaGenerator();

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setContentType("image/jpeg");
        OutputStream os = response.getOutputStream();

        BufferedImage image = captchaGenerator.generateCaptcha();
        ImageIO.write(image, "jpeg", os);

        HttpSession session = request.getSession();
        session.setAttribute("rightCode", captchaGenerator.getCaptcha());
    }
}
